var offset=0;
var limit=20;
var pagingLimit=20;//显示分页时的条数
var currentTotalElements=0;//当前显示总条数
var pageLoading=true;//是否能滚动加载
var hasShowPages=false;//是否已显示分页
var firstLoadPages=true;//分页初始化时 不自动加载
var firstLoadPages_=true;
var search_companyName=null;
var now_offset = 0;

$(function(){
	
	$(".query-jiant").click(function(){
		var src=$("#jiant").attr("src");
		if(src.indexOf("jiant2")>=0){
			$("#jiant").attr("src",ctx+"/assets/img/jiant.png");
			$(".choose").show(300);
		}else{
			$("#jiant").attr("src",ctx+"/assets/img/jiant2.png");
			$(".choose").hide(300);
		}
	});	

	$(document).on("keydown","body",function(){
		if(window.event.keyCode == 13){
			$("#searchButton").click();
		}
	});
//	$(window).scroll(function () {
//        //$(window).scrollTop()这个方法是当前滚动条滚动的距离
//        //$(window).height()获取当前窗体的高度
//        //$(document).height()获取当前文档的高度
//        var bot = 0; //bot是底部距离的高度
//        if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
//           //当底部基本距离+滚动的高度〉=文档的高度-窗体的高度时；
//        	if(pageLoading){
//        		pageLoading=false;
//        		offset+=limit;
//        		initdata(true);
//        	}
//        }
//    });
	
	initdata(false);
	
	$(".searchButton").click(function(){
		offset=0;
		var truckTypeId = $(this).attr("trucktypeId");
		var temp = $(this).parent().parent().parent().find(".tempCompanyName");
		var companyName = temp.val(); 
		var parent = $(this).parent().parent().parent().parent().parent().parent().parent().parent();
		console.debug(parent);
		var carTypeCompanyTbody=parent.children('div').children('div').children('div').children('div').children('table').children('tbody');
		var table=parent.children('div').children('div').children('div').children('div').children('table');
		var ul=parent.children('div').children('div').children('div').children('div').children('ul');
		var pageshow=$(ul[0]);
		var pagedata=$(ul[1]);
		var truckTypeName = parent.attr("typeName");
		$.ajax({
	        url : ctx+'/freight/queryTruckTypeCompany',
	        type:'GET',
	        async:false,
	        dataType : 'json',
	        data : {
	        	"truckTypeId":truckTypeId,
	        	"companyName":companyName,
	        	"pager.offset":offset,
	        	"limit":limit,
	        },
	        success : function(result){
	        	var newcontent = '';
	        	var totalElements=result.totalElements;
	        	if(totalElements>0){
	        		$(result.content).each(function(index,data){
	        			
    				var updateButton=
	        					"<div class='pull-right'><a href='#' class='btn btn-primary btn-xs updateTruckType_company' data-value='"+data.id+"' trucktypeid='"+truckTypeId+"' trucktypename='"+truckTypeName+"' companyid='"+data.companyId+"' companyname='"+data.companyName+"' areaid='"+data.areaId+"' areaName='"+data.area.name+"' >编辑</a>";
	        				
    				var deleteButton="&emsp;<a href='#'  data-value='"+data.id+"'  class='btn btn-primary  btn-xs deleteTypeCompany'>删除</a></div>";
	            	
			newcontent+="<tr>"+
		    				"<td>"+data.companyName+"</td>"+
							"<td>"+(data.area==null?"":data.area.name)+"</td>"+
							"<td>"+updateButton+deleteButton+"</td>"+
						"</tr>";
	        		});
	        	}
	        	$(carTypeCompanyTbody).html(newcontent);
	        	$(pageshow).html("<li><a>共"+totalElements+"条数据</a></li>");
        		$(pagedata).paging(totalElements, {
        			format: '[< ncnnn >]',
        			perpage: pagingLimit,
        			page:(offset/limit)+1,
        			onSelect: function (page) {
        				limit=pagingLimit;
        				offset=(page-1)*limit;
        		    	return false;
        			},
        			onFormat: function (type) {
        				switch (type) {
        				case 'block': // n and c
        					if (!this.active)
        						return '';
        					else if (this.value != this.page)
        						return '<li><a href="#">' + this.value + '</a></li>';
        					return '<li class="active"><a href="#">' + this.value + '</a></li>';
        				case 'next': // >
        					return '<li><a href="#">&rsaquo;</a><li>';
        				case 'prev': // <
        						return '<li><a href="#">&lsaquo;</a><li>';
        				case 'first': // [
        						return '<li><a href="#">&laquo;</a><li>';
        				case 'last': // ]
        						return '<li><a href="#">&raquo;</a></li>';
        				}
        			}
        		});
	        	
	        }
		});
	});
	
});
$(document).on("mouseover",".panel-heading",function(){
	$(this).css("backgroundColor","#e0e0e0");
});
$(document).on("mouseout ",".panel-heading",function(){
	$(this).css("backgroundColor","");
});
$(document).on("click",".panel-heading",function(){
	
	var carTypeId=$(this).parent().parent().attr("truckTypeId");
	var carTypeName=$(this).parent().parent().attr("typeName");
	var carTypeCompanyTbody=$(this).parent().parent().children('div').children('div').children('div').children('div').children('table').children('tbody');
	var table=$(this).parent().parent().children('div').children('div').children('div').children('div').children('table');
	var ul=$(this).parent().parent().children('div').children('div').children('div').children('div').children('ul');
	var pageshow=$(ul[0]);
	var pagedata=$(ul[1]);
	var companyName = $(this).parent().parent().find(".tempCompanyName").val();
	
	load (carTypeId, companyName, offset, limit, carTypeName, carTypeCompanyTbody, pageshow, pagedata)
	
//		$.ajax({
//	        url : ctx+'/freight/queryTruckTypeCompany',
//	        type:'GET',
//	        async:false,
//	        dataType : 'json',
//	        data : {
//	        	"truckTypeId":carTypeId,
//	        	"companyName":companyName,
//	        	"pager.offset":offset,
//	        	"limit":limit,
//	        },
//	        success : function(result){
//	        	var newcontent = '';
//	        	var totalElements=result.totalElements;
//	        	if(totalElements>0){
//	        		$(result.content).each(function(index,data){
//	        			
//    				var updateButton=
//	        					"<div class='pull-right'><a href='#' class='btn btn-primary btn-xs updateTruckType_company' data-value='"+data.id+"'  trucktypeid='"+carTypeId+"' trucktypename='"+carTypeName+"' companyid='"+data.companyId+"' companyname='"+data.companyName+"' areaid='"+data.areaId+"'  >编辑</a>";
//	        				
//    				var deleteButton="&emsp;<a href='#'  data-value='"+data.id+"'  class='btn btn-primary  btn-xs deleteTypeCompany'>删除</a></div>";
//	            	
//			newcontent+="<tr>"+
//		    				"<td>"+data.companyName+"</td>"+
//							"<td>"+(data.area==null?"":data.area.name)+"</td>"+
//							"<td>"+updateButton+deleteButton+"</td>"+
//						"</tr>";
//	        		});
//	        	}
//	        	$(carTypeCompanyTbody).html(newcontent);
//	        	$(pageshow).html("<li><a>共"+totalElements+"条数据</a></li>");
//        		$(pagedata).paging(totalElements, {
//        			format: '[< ncnnn >]',
//        			perpage: pagingLimit,
//        			page:(offset/limit)+1,
//        			onSelect: function (page) {
//        				limit=pagingLimit;
//        				offset=(page-1)*limit;
//        		    	return false;
//        			},
//        			onFormat: function (type) {
//        				switch (type) {
//        				case 'block': // n and c
//        					if (!this.active)
//        						return '';
//        					else if (this.value != this.page)
//        						return '<li><a href="#">' + this.value + '</a></li>';
//        					return '<li class="active"><a href="#">' + this.value + '</a></li>';
//        				case 'next': // >
//        					return '<li><a href="#">&rsaquo;</a><li>';
//        				case 'prev': // <
//        						return '<li><a href="#">&lsaquo;</a><li>';
//        				case 'first': // [
//        						return '<li><a href="#">&laquo;</a><li>';
//        				case 'last': // ]
//        						return '<li><a href="#">&raquo;</a></li>';
//        				}
//        			}
//        		});
//	        	
//	        }
//		});
});

function load (carTypeId, companyName, offset, limit, carTypeName, carTypeCompanyTbody, pageshow, pagedata) {
	$.ajax({
        url : ctx+'/freight/queryTruckTypeCompany',
        type:'GET',
        async:false,
        dataType : 'json',
        data : {
        	"truckTypeId":carTypeId,
        	"companyName":companyName,
        	"pager.offset":offset,
        	"limit":limit,
        },
        success : function(result){
        	var newcontent = '';
        	var totalElements=result.totalElements;
        	if(totalElements>0){
        		$(result.content).each(function(index,data){
        		var areaName = data.area == null?"--":data.area.name ;
        		var areaId = data.area == null?"--":data.area.id;
				var updateButton=
        					"<div class='pull-right'><a href='#' class='btn btn-primary btn-xs updateTruckType_company' data-value='"+data.id+"'  trucktypeid='"+carTypeId+"' trucktypename='"+carTypeName+"' companyid='"+data.companyId+"' companyname='"+data.companyName+"' areaid='"+areaId+"' areaName='"+areaName+"'  >编辑</a>";
        				
				var deleteButton="&emsp;<a href='#'  data-value='"+data.id+"'  class='btn btn-primary  btn-xs deleteTypeCompany'>删除</a></div>";
            	
		newcontent+="<tr>"+
	    				"<td>"+data.companyName+"</td>"+
						"<td>"+areaName+"</td>"+
						"<td>"+updateButton+deleteButton+"</td>"+
					"</tr>";
        		});
        	}
        	$(carTypeCompanyTbody).html(newcontent);
        	$(pageshow).html("<li><a>共"+totalElements+"条数据</a></li>");
    		$(pagedata).paging(totalElements, {
    			format: '[< ncnnn >]',
    			perpage: pagingLimit,
    			page:(offset/limit)+1,
    			onSelect: function (page) {
    				limit=pagingLimit;
    				offset=(page-1)*limit;
    		    	return false;
    			},
    			onFormat: function (type) {
    				switch (type) {
    				case 'block': // n and c
    					if (!this.active)
    						return '';
    					else if (this.value != this.page)
    						return '<li><a href="#">' + this.value + '</a></li>';
    					return '<li class="active"><a href="#">' + this.value + '</a></li>';
    				case 'next': // >
    					return '<li><a href="#">&rsaquo;</a><li>';
    				case 'prev': // <
    						return '<li><a href="#">&lsaquo;</a><li>';
    				case 'first': // [
    						return '<li><a href="#">&laquo;</a><li>';
    				case 'last': // ]
    						return '<li><a href="#">&raquo;</a></li>';
    				}
    			}
    		});
        	
        }
	});
	
	$(".panel-body").find("a[data-page]").click(function () {
		load (carTypeId, companyName, offset, limit, carTypeName, carTypeCompanyTbody, pageshow, pagedata)
	})
}

function initdata(isappend){
	$.ajax({
        url : ctx+'/freight/truckTypeData',
        type:'GET',
        async:false,
        dataType : 'json',
        data : {
        	"companyName":search_companyName,
        	"pager.offset":offset,
        	"limit":limit,
        },
        success : function(result){
        	
        	var areaContent =getAreaContent(result);
        	$("#areaId_company").html(areaContent).chosen().change(function(){});
        	
        	var newcontent = '';
        	var totalElements=result.page.totalElements;
        	if(totalElements>0){
        		$(result.page.content).each(function(index,data){
        			newcontent+="<div class='panel-group' id='accordion"+index+"' truckTypeId='"+data.id+"' typeName='"+data.typeName+"' role='tablist' aria-multiselectable='true'>"+
      			  "<div class='panel panel-default' style='border-color:#ffffff;'>"+
      				"<div class='panel-heading ' style='border-left:0px;' role='tab' id='heading"+index+"'>"+
      				  "<div class='panel-title'>"+
      					"<a data-toggle='collapse' data-parent='#accordion"+index+"' href='#collapse"+index+"' aria-expanded='true' aria-controls='collapse"+index+"'>"+
      					"<div class='col-md-3'>"+data.typeName+"</div><div class='col-md-3'>"+(data.cangointotown?"有":"无")+"</div> <div class='col-md-3'>"+data.sequence+"</div>"+
      					"</a>"+
      					"<div class='pull-right'>"+
	        					"<button href='#' trucktypeId='"+data.id+"' class='btn btn-primary btn-xs updateCarType' typeName='"+data.typeName+"' sequence='"+data.sequence+"' img='"+ data.img +"'>编辑</button>&emsp;"+
	        					(deleteTrcukType?"<button href='#'  data-value='"+data.id+"'  class='btn btn-primary btn-xs deletethis'>删除</button>&emsp;":"")+
	        					"<button class='btn btn-primary btn-xs subscribeTruckType' trucktypeId='"+data.id+"' typeName='"+data.typeName+"'>开通车型</button>"+
      					"</div>"+
      					"</div>"+
      				"</div>"+
      				"<div id='collapse"+index+"' class='panel-collapse collapse ' role='tabpanel' aria-labelledby='heading"+index+"'>";
      				if(isMainCompany){
					newcontent+="<div class='tab-content'>"+
			        				"<div class='container-fluid'>"+
			        			  		"<div class='row query-pad'>"+
			        			  			"<div class='col-xs-11' style='padding: 0px;'>"+
			        			  				"<div class='col-xs-4 input-query'>"+
				        			  				"<span>公司名称:</span>"+
				        			  				"<input type='text' class='form-control form-contb tempCompanyName'  name='companyName' placeholder='请输入公司名字'/>"+
			        			  				"</div>"+
		        			  				 "</div>"+
		        			  				 "<div class='col-xs-1' style='padding: 0px;'>"+
		        			  				 	"<div class='input-query-bttom'>"+
		        			  				 		"<button class='btn btn-primary btn-xs searchButton' style='width: 60px;font-size: 10px;height: 25px;' trucktypeId='"+data.id+"'>&emsp;查询&emsp;</button>"+
	        			  				 		"</div>"+
      			  				 		 "</div>"+
			        			  		"</div>"+
			        			  	 "</div>"+
		        			  	"</div>";
      				}
      			
      				newcontent+= "<div class='panel-body'>"+
      					"<div>"+
      						"<table class='table table-condensed table-striped'>"+
      							"<thead>"+
      								"<tr>"+
      									"<th class='col-xs-2' style='width:35%'>公司名称</th>"+
      									"<th class='col-xs-1' style='width:35%'>收费标准</th>"+
      									"<th class='col-xs-2' style='width:30%;text-align:right;padding-right:90px;'>操作</th>"+
      								"</tr>"+
      							"</thead>"+
      							"<tbody>"+
      							"</tbody>"+
      						"</table>"+
      						"<ul class='pagination pull-left pagination-sm pageshow'><li><a>共0条数据</a></li></ul>"+
      			        	"<ul class='pagination pull-left pagination-sm pagedata'></ul>"+
      			        	
      					"</div>"+
      				  "</div>"+
      				"</div>"+
      			  "</div>"+
      			"</div>";
      		});
        	}
        	$("#carTypeList").empty() // 清空已有的
        	$("#carTypeList").append(newcontent);
    		$("#carTypetotal").html("<a>共"+totalElements+" 条数据</a>");
        	if(!isappend){
        		$("#carType_tbody .grid-data").remove();
        	}
        	//$("#carType_tbody").append(newcontent);
        	$("#carType_tbody .grid-data").each(function(index,element){
        		$(element).fadeIn(200+(index*35));
        	});
        	if(!hasShowPages){
        		if(!isappend){
            		currentTotalElements=result.page.content.length;
            		pageLoading=true;
            	}else{
            		if(currentTotalElements<totalElements){
            			currentTotalElements+=result.page.content.length;
            			pageLoading=true;
            		}else{
            			pageLoading=false;
            		}
            	}
        	}
        	if(hasShowPages){
    			firstLoadPages=true;
        		$(".pageshow li a").html("共"+totalElements+" 条数据");
        		$(".pagedata").paging(totalElements, {
        			format: '[< ncnnn >]',
        			perpage: pagingLimit,
        			page:(offset/limit)+1,
        			onSelect: function (page) {
        				limit=pagingLimit;
        				
        				offset=(page-1)*limit;
        				if(!firstLoadPages){
        					initdata(false);
        				}
        				firstLoadPages=false;
        		    	return false;
        			},
        			onFormat: function (type) {
        				switch (type) {
        				case 'block': // n and c
        					if (!this.active)
        						return '';
        					else if (this.value != this.page)
        						return '<li><a href="#">' + this.value + '</a></li>';
        					return '<li class="active"><a href="#">' + this.value + '</a></li>';
        				case 'next': // >
        					return '<li><a href="#">&rsaquo;</a><li>';
        				case 'prev': // <
        						return '<li><a href="#">&lsaquo;</a><li>';
        				case 'first': // [
        						return '<li><a href="#">&laquo;</a><li>';
        				case 'last': // ]
        						return '<li><a href="#">&raquo;</a></li>';
        				}
        			}
        		});
        	}else{
        		//滚动达到pagingLimit条开始显示分页
        		if(currentTotalElements==pagingLimit){
            		pageLoading=false;
            		hasShowPages=true;
            		$(".pageshow").show();
            		$(".pagedata").show();
            		$(".pageshow li a").html("共"+totalElements+" 条数据");
            		$(".pagedata").paging(totalElements, {
            			format: '[< ncnnn >]',
            			perpage: pagingLimit,
            			onSelect: function (page) {
            				limit=pagingLimit;
            				offset=(page-1)*limit;
            				if(!firstLoadPages){
            					initdata(false);
            				}
            				firstLoadPages=false;
            		    	return false;
            			},
            			onFormat: function (type) {
            				switch (type) {
            				case 'block': // n and c
            					if (!this.active)
            						return '';
            					else if (this.value != this.page)
            						return '<li><a href="#">' + this.value + '</a></li>';
            					return '<li class="active"><a href="#">' + this.value + '</a></li>';
            				case 'next': // >
            					return '<li><a href="#">&rsaquo;</a><li>';
            				case 'prev': // <
            						return '<li><a href="#">&lsaquo;</a><li>';
            				case 'first': // [
            						return '<li><a href="#">&laquo;</a><li>';
            				case 'last': // ]
            						return '<li><a href="#">&raquo;</a></li>';
            				}
            			}
            		});
            	}
        	}
        }
	});
}

Date.prototype.Format = function(fmt) 
{ 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt; 
};
function getAreaContent(result){
	var areaContent = '';
	var areaList = result.areaList;
	$(areaList).each(function(index,data){
		areaContent+="<option value='"+data.id+"'>"+data.name+"</option>"
	});
	return areaContent;
};

